package com.youth.fund.hk.hostManager.lucene.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.document.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.youth.fund.hk.hostManager.lucene.core.SearchEngineCore;
import com.youth.fund.hk.hostManager.lucene.datamodel.ContentModel;
import com.youth.fund.hk.hostManager.lucene.service.SearchService;
import com.youth.fund.hk.hostManager.lucene.webcontent.PackContentObject;
import com.youth.fund.hk.hostManager.lucene.webcontent.WebContent;

@Service("SearchService")
public class SearchServiceImpl implements SearchService {
	
	@Value("${lucene.index_path}")
	private String luceneindex_path;
	
	private SearchEngineCore core ;

	@Override
	public void addIndex(String url) {
		if(core == null)
		{
			core = SearchEngineCore.getInstance(luceneindex_path);
		}
		
		WebContent wc = new WebContent();

		ContentModel model = wc.getContentFromSite(url);

		Document doc = PackContentObject.convertContentToDoc(model);

		core.addIndex(doc);
	}

	@Override
	public void deleteIndex(String url) {
		if(core == null)
		{
			core = SearchEngineCore.getInstance(luceneindex_path);
		}
		WebContent wc = new WebContent();

		ContentModel model = wc.getContentFromSite(url);

		Document doc = PackContentObject.convertContentToDoc(model);

		core.deleteIndex(doc);
	}

	@Override
	public void updateIndex(String url) {
		if(core == null)
		{
			core = SearchEngineCore.getInstance(luceneindex_path);
		}
		WebContent wc = new WebContent();

		ContentModel model = wc.getContentFromSite(url);

		Document doc = PackContentObject.convertContentToDoc(model);

		core.updateIndex(doc);
	}

	@Override
	public void deleteAll() {
		if(core == null)
		{
			core = SearchEngineCore.getInstance(luceneindex_path);
		}
		core.deleteAll();
	}

	@Override
	public List<ContentModel> queryIndex(String keyword) {
		if(core == null)
		{
			core = SearchEngineCore.getInstance(luceneindex_path);
		}
		List<ContentModel> resultList = new ArrayList<ContentModel>();

//		List<Document> docList = core.queryIndex(keyword);
//
//		for (Document doc : docList) {
//			resultList.add(PackContentObject.convertDocToContent(doc));
//		}
		resultList = core.queryIndexHighLighter(keyword);

		return resultList;
	}

}
